package com.xyy.lesson.timingpractice;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends Activity {

    private TextView textView;
    private LogPrint logPrint = LogPrint.getInstance();

    //三种定时方法
    //private Timer mTimer = new Timer();  //单线程，可以调度多个任务，不可对UI控件做操作
    Handler mtimerHandler = new Handler();
    //ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();//线程池
    //另一种定时任务可通过Receiver和Service结合实现

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.textview);

        logPrint.setIsPrintDebugInfo(true);

        long delay = 0;  //延迟时间
        long intevalPeriod = 1 * 1000;  //间隔时间
        //mTimer.scheduleAtFixedRate(task, delay, intevalPeriod);

        mtimerHandler.postDelayed(runnable, 1000);  //延迟1秒执行1次runnable

        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        //service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);

        /*
        TimeUnit.DAYS;               //天
        TimeUnit.HOURS;             //小时
        TimeUnit.MINUTES;           //分钟
        TimeUnit.SECONDS;           //秒
        TimeUnit.MILLISECONDS;      //毫秒
        TimeUnit.MICROSECONDS;      //微妙
        TimeUnit.NANOSECONDS;       //纳秒
        */
    }

    private String infoPrint = "";
    private int infoCount = 0;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                mtimerHandler.postDelayed(this, 1000);  //一秒
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                String times = format.format(new Date(System.currentTimeMillis()));
                infoPrint = infoPrint + String.valueOf(infoCount) + ":" + times + " Timer定时器正常运行，间隔时间1秒" + "\n";
                textView.setText(infoPrint);
                logPrint.saveLogInfoToSD( String.valueOf(infoCount) + ":" + " Timer定时器正常运行，间隔时间1秒");
                textViewLisCcount();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("exception...");
            }
        }
    };

    //该方法定时，不能对UI控件做操作。
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                String times = format.format(new Date(System.currentTimeMillis()));
                infoPrint = infoPrint + String.valueOf(infoCount) + ":" + times + " Timer定时器正常运行，间隔时间1秒" + "\n";
                textView.setText(infoPrint);
                logPrint.saveLogInfoToSD( String.valueOf(infoCount) + ":" + " Timer定时器正常运行，间隔时间1秒");
                textViewLisCcount();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("exception...");
            }
        }
    };

    public void textViewLisCcount(){

        infoCount = infoCount + 1;
        if (infoCount==12){infoCount=0;infoPrint="";}

    }

    @Override
    public void onBackPressed() {
        Log.e("MainActivity","onBackPressed");
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("确认要退出吗？")
                .setNegativeButton(android.R.string.cancel, null)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override public void onClick(DialogInterface dialogInterface, int i) {

                        SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor=preferences.edit();
                        editor.putInt("jiemianselect", 0);
                        editor.commit();

                        finish();

                    }
                });
        builder.create().show();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        //mTimer.cancel();
        mtimerHandler.removeCallbacks(runnable);
    }
}
